<?php 
class UserController extends Slog_Controller 
{
	public function publicLogin()
	{
		// Obtenemos la url de retorno
		if (!Slog::session()->referer) {
			$referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '?q=';
			if (strstr('user/login', $referer)) {
				$referer = '?q=';
			}
			Slog::session()->referer = $referer;
		}
		
		// Autentificamos usuario
		if (isset($_POST['email']) && isset($_POST['password'])) {
			$email = trim(addslashes($_POST['email']));
			$passowrd = trim(addslashes($_POST['password']));
			
			// Comprobamos usuario y contraseña en la base de datos
			$sql = "
				SELECT id_user, nick, email
				FROM slog_users
				WHERE email = '$email'
				AND password = MD5('$passowrd')
			";
			if ($user = $db->fetch($sql)) {
				// Login OK
				$_SESSION['user'] = $user;
				$referer = $_SESSION['referer'];
				unset($_SESSION['referer']);
				header('Location: ' . $referer);
				exit();
			} else {
				// Login Error
				unset($_SESSION['user']);
				$this->login_message = 'Email o contraseña incorrectas';
			}
		}
		
		$this->title = 'Login | ' . $this->title;
	}
	
	public function publicLogout()
	{
		// Obtenemos url de retorno
		$referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '?q=';
		if (strstr('user/login', $referer)) {
			$referer = '?q=';
		}
		
		// Hacemos logout
		Slog_User::logout();
		
		// Volvemos
		$this->redirect($referer);
	}
}
